import apiClient from '@/lib/interceptor';

// 定义系统设置接口
export interface SystemSetting {
    settingId: number;
    settingName: string;
    settingValue: string;  // 改为 string 类型，因为后端返回的是字符串
}

// 定义API响应接口
interface ApiResponse<T> {
    code: number;
    msg: string;
    data: T;
}

/**
 * 获取系统设置
 * @returns 系统设置列表
 */
export const getSystemSettings = async () => {
    try {
        const response = await apiClient.get<ApiResponse<SystemSetting[]>>('/settings');
        
        console.log('获取系统设置响应:', response);

        if (response.data.code !== 1) {
            throw new Error(response.data.msg || '获取系统设置失败');
        }

        return response.data.data;  // 直接返回 data 数组
    } catch (error: any) {
        console.error('获取系统设置失败:', error);
        if (error.response) {
            throw new Error(
                error.response.data?.msg || 
                error.response.data?.message || 
                '服务器返回错误'
            );
        } else if (error.request) {
            throw new Error('服务器未响应');
        } else {
            throw error;
        }
    }
};

/**
 * 更新系统设置
 * @param settingId 设置ID
 * @param value 设置值 0关闭 1开启
 */
export const updateSystemSetting = async (settingId: number, value: number) => {
    try {
        console.log('发送更新设置请求:', { settingId, settingValue: value });
        
        // 使用 URLSearchParams 构建查询参数
        const params = new URLSearchParams({
            settingId: settingId.toString(),
            settingValue: value.toString()
        });

        const response = await apiClient.put<ApiResponse<null>>(
            `/settings?${params.toString()}`
        );

        console.log('更新设置响应:', response);

        if (response.data.code !== 1) {
            throw new Error(response.data.msg || '更新系统设置失败');
        }

        return response.data;
    } catch (error: any) {
        console.error('更新系统设置失败:', error);
        if (error.response) {
            throw new Error(
                error.response.data?.msg || 
                error.response.data?.message || 
                '服务器返回错误'
            );
        } else if (error.request) {
            throw new Error('服务器未响应');
        } else {
            throw error;
        }
    }
};

/**
 * 获取特定系统设置
 * @param settingName 设置名称
 * @returns 设置值
 */
export const getSpecificSetting = async (settingName: string): Promise<string | null> => {
    try {
        const settings = await getSystemSettings();
        const setting = settings.find(s => s.settingName === settingName);
        return setting ? setting.settingValue : null;
    } catch (error) {
        console.error('获取特定设置失败:', error);
        throw error;
    }
}; 